﻿using System;
using System.Collections.Generic;
using System.Text;
using Commerce.Common;
using System.Xml;
using System.Xml.XPath;
using System.Text.RegularExpressions;
using SubSonic;


namespace CommerceForUmbraco.xsltExtensions
{
    public class CommerceForUmbracoExtension
    {

     


        public static XPathNodeIterator ProductDetail(string productID)
        {

            try
            {

            //Pull product from Subsonic object.
            Product thisProduct = GetProduct(productID);

            //Create XML object
            XmlDocument doc = new XmlDocument();
            XmlElement root = (XmlElement)doc.AppendChild(doc.CreateElement("Product"));

            foreach (TableSchema.TableColumnSetting col in thisProduct.GetColumnSettings())
            {
                string colValue = string.Empty;
                string colName = thisProduct.GetSchema().GetColumn(col.ColumnName).PropertyName;

                if (col.CurrentValue != null)
                    colValue = col.CurrentValue.ToString();


                XmlAttribute ItemName = doc.CreateAttribute(colName, "");
                ItemName.Value = colValue;
                root.Attributes.Append(ItemName);
            }




            XmlElement CategoryList = (XmlElement)root.AppendChild(doc.CreateElement("CategoryList"));


            foreach (Category category in thisProduct.GetCategoryCollection())
            {

                XmlElement elem = doc.CreateElement("Category");
                XmlAttribute CategoryName = doc.CreateAttribute("CategoryName", "");
                CategoryName.Value = category.CategoryName;
                elem.Attributes.Append(CategoryName);

                XmlAttribute CategoryID = doc.CreateAttribute("CategoryID", "");
                CategoryID.Value = Convert.ToString(category.CategoryID);
                elem.Attributes.Append(CategoryID);

                XmlAttribute CategoryGUID = doc.CreateAttribute("CategoryGUID", "");
                CategoryGUID.Value = Convert.ToString(category.CategoryGUID);
                elem.Attributes.Append(CategoryGUID);

               CategoryList.AppendChild(elem);
            }



            return doc.CreateNavigator().Select("/*");

            }
            catch (Exception e)
            {
                // If there's an exception we'll output an error element instead
                XmlDocument errorDoc = new XmlDocument();
                errorDoc.LoadXml(String.Format("<error>{0}</error>", System.Web.HttpUtility.HtmlEncode(e.ToString())));
                return errorDoc.CreateNavigator().Select(".");
            }
        }


        public static XPathNodeIterator CategoryList()
        {

            try
            {

            //Create XML object
            XmlDocument doc = new XmlDocument();

            XmlElement CategoryList = (XmlElement)doc.AppendChild(doc.CreateElement("CategoryList"));


            foreach (Category category in  new CategoryCollection().Load())
            {

                XmlElement elem = doc.CreateElement("Category");
                XmlAttribute CategoryName = doc.CreateAttribute("CategoryName", "");
                CategoryName.Value = category.CategoryName;
                elem.Attributes.Append(CategoryName);

                XmlAttribute CategoryID = doc.CreateAttribute("CategoryID", "");
                CategoryID.Value = Convert.ToString(category.CategoryID);
                elem.Attributes.Append(CategoryID);

                XmlAttribute CategoryGUID = doc.CreateAttribute("CategoryGUID", "");
                CategoryGUID.Value = Convert.ToString(category.CategoryGUID);
                elem.Attributes.Append(CategoryGUID);

               CategoryList.AppendChild(elem);
            }



            return doc.CreateNavigator().Select("/*");

            }
            catch (Exception e)
            {
                // If there's an exception we'll output an error element instead
                XmlDocument errorDoc = new XmlDocument();
                errorDoc.LoadXml(String.Format("<error>{0}</error>", System.Web.HttpUtility.HtmlEncode(e.ToString())));
                return errorDoc.CreateNavigator().Select(".");
            }
        }


        public static XPathNodeIterator ManufacturerList()
        {

            try
            {

                //Create XML object
                XmlDocument doc = new XmlDocument();

                XmlElement ManufacturerList = (XmlElement)doc.AppendChild(doc.CreateElement("ManufacturerListList"));


                foreach (Manufacturer manufacturer in new ManufacturerCollection().Load())
                {

                    XmlElement elem = doc.CreateElement("Manufacturer");
                    XmlAttribute Manufacturer = doc.CreateAttribute("Manufacturer", "");
                    Manufacturer.Value = manufacturer.ManufacturerX;
                    elem.Attributes.Append(Manufacturer);

                    XmlAttribute ManufacturerID = doc.CreateAttribute("ManufacturerID", "");
                    ManufacturerID.Value = Convert.ToString(manufacturer.ManufacturerID);
                    elem.Attributes.Append(ManufacturerID);

                    ManufacturerList.AppendChild(elem);
                }

                return doc.CreateNavigator().Select("/*");

            }
            catch (Exception e)
            {
                // If there's an exception we'll output an error element instead
                XmlDocument errorDoc = new XmlDocument();
                errorDoc.LoadXml(String.Format("<error>{0}</error>", System.Web.HttpUtility.HtmlEncode(e.ToString())));
                return errorDoc.CreateNavigator().Select(".");
            }
        }




        public static string AddToCart(string productID, string quantity)
        {

            try
            {


                //Pull product from Subsonic object.
                Product prod = GetProduct(productID);

                 prod.Quantity = int.Parse(quantity);
                OrderController.AddItem(prod);


                return "Success";

            }
            catch (Exception e)
            {
                // If there's an exception we'll output an error element instead
               //XmlDocument errorDoc = new XmlDocument();
                //errorDoc.LoadXml(String.Format("<error>{0}</error>", System.Web.HttpUtility.HtmlEncode(e.ToString())));
                return "Failure";
            }
        
        }


        private static Product GetProduct (string p)

        {

            Commerce.Common.Product product = null;
            try
            {

                int productID;
                string productSku;
                Guid productGUID;

                string sProductGUID = "";

                if (IsGUID(p))
                    sProductGUID = p;

                if (int.TryParse(p, out productID) == false)
                    productID = 0;

                productSku = p;

                if (sProductGUID != string.Empty)
                {
                    productGUID = new Guid(sProductGUID);
                    product = ProductController.GetProductDeepByGUID(productGUID);
                }
                else if (productID != 0)
                {
                    product = ProductController.GetProductDeep(productID);
                }
                else if (productSku != string.Empty)
                {
                    product = ProductController.GetProductDeep(productSku);
                }
            
                //make sure we have a product
                TestCondition.IsTrue(product.IsLoaded, "Invalid url/product id");
                

            }
            catch (Exception)
            {
                //To Do.
                //Response.Write(ex.Message + ex.StackTrace);
                //throw ex;
                //ExceptionPolicy.HandleException(ex, "Application Exception");
                //Response.Redirect(Page.ResolveUrl("~/ExceptionPage.aspx"), false);
            }

            return product;
        }


        

        public static bool IsGUID(string expression)
        {
            if (expression != null)
            {
                Regex guidRegEx = new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");

                return guidRegEx.IsMatch(expression);
            }
            return false;
        }



    }
}